package com.free4inno.knowledgems.service;

import com.free4inno.knowledgems.constants.UserConstants;
import com.free4inno.knowledgems.dao.ResourceDAO;
import com.free4inno.knowledgems.domain.Resource;
import com.free4inno.knowledgems.utils.ImageUtils;
import com.free4inno.knowledgems.utils.PraseMimeMessage;
import com.sun.mail.pop3.POP3Folder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.*;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Objects;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/mail")
public class ParseMailService {

    @Autowired
    private ResourceDAO resourceDao;

    @Autowired
    private ResourceEsService esService;

    private String lastTitle = "";

    @RequestMapping("/parsemail")
    public void run() {
        // 如邮箱地址为telestar@163.com ，则这里的名称只需要填telestar
        //this.parsemail01("zhi_support", "NVEYIDDNSEBPUUXM");
        this.parsemail01("zl_support", "GMTEYPXUKXASZOAO");
        //账号:zhi_support@163.com 密码:Telestar1234
    }

    public void parsemail01(String mailname, String pwd) {
        try {
            // 链接邮箱
            Session session = Session.getInstance(new Properties());
            Store store = session.getStore("pop3");
            // 这里163.com 可以更改，你用qq 或者其他邮箱，就更改其他的.com
            store.connect("pop3.163.com", 110, mailname, pwd);
            Folder folder = store.getFolder("inbox");
            folder.open(Folder.READ_ONLY);
            Message message[] = folder.getMessages();
            POP3Folder inbox = (POP3Folder) folder;
            PraseMimeMessage pmm = null;
            System.out.println(" 正在收取邮箱" + mailname + "的邮件，开始下载相应附件到本地");
            pmm = new PraseMimeMessage((MimeMessage) message[message.length - 1]);
            System.out.println("subject: " + pmm.getSubject());
            if(Objects.equals(pmm.getSubject(), lastTitle))return;
            else lastTitle=pmm.getSubject();
            System.out.println("containAttachment: " + pmm.isContainAttach((Part) message[message.length - 1]));
            System.out.println("form: " + pmm.getFrom());
            System.out.println("to: " + pmm.getMailAddress("to"));
            pmm.setDateFormat("yy年MM月dd日 HH:mm");
            pmm.getMailContent((Part) message[message.length - 1]);
            System.out.println("bodycontent: \r\n" + pmm.getBodyText());
            String text=pmm.getBodyText();
            Pattern text_html = Pattern.compile("(<[\\s\\S]*>)");
            Matcher text_matcher = text_html.matcher(text);
            boolean resultImg = text_matcher.find();
            if (resultImg) {
                text = text_matcher.group(1);
            }
            Integer userId = 163;
            Resource resource = new Resource();
            resource.setUserId(userId);
            resource.setCreateTime(new Timestamp(new Date().getTime()));
            resource.setEditTime(new Timestamp(new Date().getTime()));
            resource.setTitle(pmm.getSubject());
            resource.setText(text);
            resource.setPermissionId(1); //默认为不公开资源
            resource.setSuperior(0);
            //resource.setGroupId(group);
            //resource.setLabelId(label);
            //resource.setContents(contents);
            resourceDao.saveAndFlush(resource);
            esService.addResourceES(resource.getId());
                File file = new File("/Users/liuxinyuan/Desktop/zhi/knowledgems/src/main/webapp/mail");
                if (!file.exists()) {
                    file.mkdirs();
                }
                pmm.setAttachPath(file.toString());
                pmm.saveAttachMent((Part) message[0]);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

